import 'dart:io';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/user.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/event.dart';
import 'package:geomancy/tools/upload.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/gallery_util/index.dart';
import 'package:geomancy/widgets/stroke_text.dart';
import 'package:go_router/go_router.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';

class RegisterAvatarPage extends StatefulWidget {
  const RegisterAvatarPage({super.key});

  @override
  State<RegisterAvatarPage> createState() => _RegisterNicknamePageState();
}

class _RegisterNicknamePageState extends State<RegisterAvatarPage> {
  File? avatarFile;

  @override
  void initState() {
    super.initState();
    eventListener.on(Constant.CROPAVATAR, (arg) {
      setState(() {
        avatarFile = arg;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    eventListener.off(Constant.CROPAVATAR);
  }

  ///上传头像
  Future<String?> uploadAvatar() async {
    if (avatarFile == null) return null;
    try {
      final result = await QiNiu.uploadImage(context, file: avatarFile!, type: UploadBucketType.userAvatar);
      return result?.url;
    } catch(e) {
      return null;
    }
  }

  ///更新用户信息
  Future updateUserInfo() async {
    try {
      EasyLoading.show(status: '注册中...');
      final localUserInfo = context.read<UserProvider>().getUserInfo;
      if (localUserInfo == null) {
        context.go('/');
        return;
      }
      final avatarUrl = await uploadAvatar();
      final UserUpdateAPIData userParams = UserUpdateAPIData.fromJson({
        "username": localUserInfo.username,
        "sex": localUserInfo.sex,
        "phone": localUserInfo.phone,
        "birthday": localUserInfo.birthday,
        "zodiac": Utils.getZodiacIndex(localUserInfo.birthday!).toString(),
        "avatar": avatarUrl
      });
      if (mounted) {
        final bool result = await UserAPI.update(context: context, user: userParams);
        if (result && mounted) {
          context.go('/');
        }
      }
    } catch(e) {
      //...
    } finally {
      EasyLoading.dismiss();
    }
  }

  void openGalleryHandle() {
    GalleryUtils.openGallery(context,
      scene: GalleryScene.registerAvatar,
      type: RequestType.image,
      maxCount: 1
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context, showActions: false),
      backgroundColor: ColorStyle.pageDefaultColor,
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.only(top: 100.w, left: Constant.PAGEPADDING.w, right: Constant.PAGEPADDING.w),
          child: DottedBorder(
            borderType: BorderType.RRect,
            strokeWidth: 5.w,
            radius: Radius.circular(60.w),
            dashPattern: [12.w, 6.w],
            color: ColorStyle.borderColor,
            child: Container(
              width: double.infinity,
              height: 1050.w,
              padding: EdgeInsets.only(top: 110.w, bottom: 60.w),
              decoration: BoxDecoration(
                color: ColorStyle.themeLightColor,
                borderRadius: BorderRadius.all(Radius.circular(55.w)),
              ),
              child: Column(
                children: [
                  StrokeText(txt: '设置头像', strokeWidth: 8.sp, fontSize: 60.sp, color: ColorStyle.themeColor, fontFamily: 'fontZKKLT'),
                  SizedBox(height: 130.w),
                  GestureDetector(
                    onTap: openGalleryHandle,
                    child: Container(
                      width: 230.w,
                      height: 230.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: const Color.fromRGBO(72, 58, 44, 0.6),
                          border: Border.all(width: 6.w, color: const Color.fromRGBO(255, 85, 85, 1)),
                          borderRadius: BorderRadius.all(Radius.circular(115.w))
                      ),
                      child: Stack(
                        children: [
                          if (avatarFile != null)
                            ClipOval(
                              child: SizedBox(
                                width: 230.w,
                                height: 230.w,
                                child: Image.file(avatarFile!, fit: BoxFit.contain),
                              ),
                            ),
                          Center(child: Image.asset('assets/icons/icon_camera.png', width: 70.w))
                        ],
                      )
                    ),
                  ),
                  const Expanded(child: SizedBox()),
                  CommonBtnWidget(size: Size(510.w, 100.w), txt: '确认', onTap: updateUserInfo)
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
